package com.zhouwr.simulator;

import com.zhouwr.common.utils.HexConvertUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Client,channelActive");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("Client,接收到服务端发来的消息:" + msg.toString());
        String data = "" +
                "01 03 f4 00 c3 00 c1 00 c2 00 c0 00 bf 00 c2 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 fc 19 00 c3 00 00 66 a3";

        // 0xFF 0x01 OX00
        byte[] respose = HexConvertUtil.hexStringToBytes(data + " 7e");
        assert respose != null;
        ctx.writeAndFlush(respose);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        log.info("Client,Idle:" + event.state());
        switch (event.state()) {
            case READER_IDLE:
                break;
            case WRITER_IDLE:
                ctx.write("heart");
                ctx.writeAndFlush("~");
                break;
            case ALL_IDLE:
                break;
            default:
                super.userEventTriggered(ctx, evt);
                break;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("Client,exceptionCaught");
        cause.printStackTrace();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("Client,channelInactive");
    }
}
